package com.truckdispatching.image;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.media.ThumbnailUtils;

public class ImageDownloadTask extends ImageTask {

	private final int TIME_OUT = 10000;// 网络超时时间

	private final int MAX_TRY_COUNT = 3;// 重试次数

	public ImageDownloadTask(ImageTask task) {
		super(task);
	}

	public ImageDownloadTask(File saveFile, String imageUrl) {
		super(saveFile, imageUrl);
	}

	@Override
	public void run() {
		if (isCancel) {
			return;
		}
		InputStream is = null;
		FileOutputStream fos = null;
		HttpURLConnection conn = null;
		Bitmap bitmap = null;
		if (mImageFile.exists()) {
			if (mListener != null) {
				if (isReturnBitmap) {
					Options o = new Options();
					o.inJustDecodeBounds = true;
					o.inPreferredConfig = Bitmap.Config.RGB_565;
					bitmap = BitmapFactory.decodeFile(mImageFile.getAbsolutePath(), o);
					int width = o.outWidth;
					Options o1 = new Options();
					o1.inPreferredConfig = Bitmap.Config.RGB_565;
					int scale =	width / 160;
					if(scale > 1){
						o1.inSampleSize = scale;
					}
					bitmap = BitmapFactory.decodeFile(mImageFile.getAbsolutePath(), o1);
					if (bitmap != null) {
						mListener.success(this, bitmap);
					} else {
						mListener.fail(this);
					}
				} else {
					mListener.success(this, null);
				}
			}
			return;
		}
		File tempFile = new File(mImageFile.getAbsolutePath() + ".temp");
		int leftTryCount = MAX_TRY_COUNT;
		while (leftTryCount > 0) {
			if (isCancel) {
				return;
			}
			try {
				URL url = new URL(mImageUrl);
				conn = (HttpURLConnection) url.openConnection();
				if (conn != null) {
					// 解决EOFException，android SDK的一个BUG
					System.setProperty("http.keepAlive", "false");
					conn.setConnectTimeout(TIME_OUT);
					conn.setUseCaches(false);
					conn.setRequestMethod("GET");
					conn.connect();
					if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						is = conn.getInputStream();
						if (tempFile.exists()) {
							tempFile.delete();
						}
						try {
							tempFile.createNewFile();
						} catch (IOException ex) {

						}

						if (tempFile.exists()) {
							fos = new FileOutputStream(tempFile);
							byte[] buff = new byte[1024];
							int read = is.read(buff);
							while (read != -1) {
								if (isCancel) {
									return;
								}
								fos.write(buff, 0, read);
								read = is.read(buff);
							}
							fos.flush();
							tempFile.renameTo(mImageFile);
							if (mListener != null) {
								if (isReturnBitmap) {
									bitmap = BitmapFactory.decodeFile(mImageFile.getAbsolutePath(), getBitmapOptions());
									if (bitmap != null) {
										Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, 160, 96);
										bitmap.recycle();
										mListener.success(this, thumb);
										return;
									}
								} else {
									mListener.success(this, null);
									return;
								}
							}
						} else {
							// 无存储卡直接通知回调
							if (mListener != null) {
								if (isReturnBitmap) {
									bitmap = BitmapFactory.decodeStream(is, null, getBitmapOptions());
									Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, 160, 96);
									bitmap.recycle();
									if (thumb != null) {
										mListener.success(this, thumb);
										return;
									}
								} else {
									mListener.success(this, null);
									return;
								}
							}
						}
					}
				}
			} catch (Exception e) {
				if (tempFile != null && tempFile.exists()) {
					tempFile.delete();
				}
			} finally {
				try {
					if (is != null) {
						is.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					if (null != fos) {
						fos.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (conn != null) {
					conn.disconnect();
					conn = null;
				}
				leftTryCount--;
			}
		}
		if (mListener != null) {
			mListener.fail(this);
		}
	}
}
